package com.zmv.buzzmeback;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class CallActivity extends Activity {
	/** Called when the activity is first created. */
	private CallActivity self;
	GridView mKeypadGrid;
	KeypadAdapter mKeypadAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		self = this;
		// Get reference to the keypad button GridView
		mKeypadGrid = (GridView) findViewById(R.id.grdButtons);

		// Create Keypad Adapter
		mKeypadAdapter = new KeypadAdapter(this);

		// Set adapter of the keypad grid
		mKeypadGrid.setAdapter(mKeypadAdapter);
		// Set button click listener of the keypad adapter
		mKeypadAdapter.setOnButtonClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Button btn = (Button) v;
				// Get the KeypadButton value which is used to identify the
				// keypad button from the Button's tag
				KeypadButton keypadButton = (KeypadButton) btn.getTag();

				// Process keypad button
				ProcessKeypadInput(keypadButton, v);
			}

		});

		mKeypadGrid.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long id) {
				// This will not help us catch button clicks!
			}
		});
	}

	private void ProcessKeypadInput(KeypadButton keypadButton, View v) {
		String text = keypadButton.getText().toString();
		TextView textView = (TextView) findViewById(R.id.callNumber);
		switch (keypadButton) {
		case CALL: // Handle call

			if (textView.getText().length() <= 0) {
				Toast.makeText(self,
						getString(R.string.message_enter_a_number_first),
						Toast.LENGTH_LONG).show();
			} else {
				callNumber(v);
			}
			break;
		case DELETE:
			if (textView.getText().length() > 0) {
				textView.setText(textView.getText().subSequence(0,
						textView.getText().length() - 1));
			}
			break;
		default:
			textView.setText(textView.getText().toString() + text);
			break;
		}

	}

	public void callNumber(View view) {
		new MakeCall()
				.execute(new String[] {
						getString(R.string.constant_my_number),
						((TextView) findViewById(R.id.callNumber)).getText()
								.toString() });
	}

	private class MakeCall extends AsyncTask<String, Void, Boolean> {
		@Override
		protected Boolean doInBackground(String... numbers) {
			return call(numbers[0], numbers[1]);
		}

		@Override
		protected void onPostExecute(Boolean success) {
			if (success) {
				Toast.makeText(self,
						getString(R.string.message_call_request_sent),
						Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(self, getString(R.string.message_call_failed),
						Toast.LENGTH_LONG).show();
			}
		}
	}

	private Boolean call(String fromNumber, String toNumber) {
		try {
			// prepare http client and parameters
			HttpClient httpclient = new DefaultHttpClient();
			List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
			formparams.add(new BasicNameValuePair(
					getString(R.string.constant_vbuzzer_paramname_username),
					getString(R.string.constant_vbuzzer_username)));
			formparams.add(new BasicNameValuePair(
					getString(R.string.constant_vbuzzer_paramname_password),
					getString(R.string.constant_vbuzzer_password)));
			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
					formparams,
					getString(R.string.constant_vbuzzzer_http_parameter_encoding));
			HttpPost httppost = new HttpPost(
					getString(R.string.constant_vbuzzer_auth_url));
			httppost.setEntity(entity);
			HttpResponse response = httpclient.execute(httppost);
			// release resources
			if (response.getEntity() != null) {
				response.getEntity().consumeContent();
			}
			/*
			 * HttpGet httpget = new HttpGet( (new StringBuilder(
			 * getString(R.string.constant_vbuzzer_bypass_url)))
			 * .append(response .getFirstHeader(
			 * getString(R.string.constant_vbuzzer_bypass_url_appender_header))
			 * .getValue()).toString()); httppost.abort(); response =
			 * httpclient.execute(httpget); httpget.abort();
			 */
			formparams = new ArrayList<BasicNameValuePair>();
			formparams.add(new BasicNameValuePair(
					getString(R.string.constant_vbuzzer_paramname_from_number),
					fromNumber));
			formparams.add(new BasicNameValuePair(
					getString(R.string.constant_vbuzzer_paramname_to_number),
					toNumber));
			entity = new UrlEncodedFormEntity(
					formparams,
					getString(R.string.constant_vbuzzzer_http_parameter_encoding));
			httppost = new HttpPost(
					getString(R.string.constant_vbuzzer_call_url));
			httppost.setEntity(entity);
			response = httpclient.execute(httppost);
			// release resources
			if (response.getEntity() != null) {
				response.getEntity().consumeContent();
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
}